import request from '@/utils/request'
import axios from 'axios'

// 查询设备列表
export function listDevice(query) {
  return request({
    url: '/iot/device/list',
    method: 'get',
    params: query
  })
}

// 查询设备详细
export function getDevice(deviceId) {
  return request({
    url: '/iot/device/' + deviceId,
    method: 'get'
  })
}

// 新增设备
export function addDevice(data) {
  return request({
    url: '/iot/device',
    method: 'post',
    data: data
  })
}

// 修改设备
export function updateDevice(data) {
  return request({
    url: '/iot/device',
    method: 'put',
    data: data
  })
}

// 删除设备
export function delDevice(deviceId) {
  return request({
    url: '/iot/device/' + deviceId,
    method: 'delete'
  })
}

// 导出设备
export function exportDevice(query) {
  return request({
    url: '/iot/device/export',
    method: 'get',
    params: query
  })
}

export function queryDeviceIdAsync(form, cb) {
  if (form.deviceId.length < 3 || form.deviceId.length >= 15) {
    cb([]);
    return;
  }

  if (form.source !== null) {
    form.source.cancel("cancel query deviceId");
  }

  form.source = axios.CancelToken.source();

  request('/query/data/list/devices/' + form.deviceId, {
    cancelToken: form.source.token
  }).then(rsp => {
    let result = rsp.data;
    console.log(result);
    cb(result.map(d => ({"value": d})));
  }).catch(e => {
    if (axios.isCancel(e)) {
      console.log('Request canceled', e.message);
    } else {
      console.log("query deviceIds error", e);
    }
    cb([]);
  });
}

